/**
 * 系统消息管理服务层
 */

// 模拟用户列表数据
const mockUsers = [
  {
    id: 1,
    name: '林晓东',
    role: '应急指挥组长',
    department: '应急指挥中心',
    phone: '138-0000-1001',
    email: 'linxiaodong@emc.gov',
    color: '#409EFF'
  },
  {
    id: 2,
    name: '王秀英',
    role: '流调组长',
    department: '流行病学调查组',
    phone: '138-0000-1002',
    email: 'wangxiuying@emc.gov',
    color: '#67C23A'
  },
  {
    id: 3,
    name: '陈国华',
    role: '卫生监督员',
    department: '卫生监督科',
    phone: '138-0000-1003',
    email: 'chenguohua@emc.gov',
    color: '#E6A23C'
  },
  {
    id: 4,
    name: '刘敏慧',
    role: '应急专员',
    department: '应急管理科',
    phone: '138-0000-1004',
    email: 'liuminhui@emc.gov',
    color: '#F56C6C'
  },
  {
    id: 5,
    name: '杨建国',
    role: '疾控专家',
    department: '疾病控制科',
    phone: '138-0000-1005',
    email: 'yangjianguo@emc.gov',
    color: '#909399'
  },
  {
    id: 6,
    name: '赵文静',
    role: '流调专员',
    department: '流行病学调查组',
    phone: '138-0000-1006',
    email: 'zhaowenjing@emc.gov',
    color: '#409EFF'
  },
  {
    id: 7,
    name: '孙立伟',
    role: '信息管理员',
    department: '信息管理科',
    phone: '138-0000-1007',
    email: 'sunliwei@emc.gov',
    color: '#67C23A'
  },
  {
    id: 8,
    name: '周美玲',
    role: '实验室主任',
    department: '检验检测中心',
    phone: '138-0000-1008',
    email: 'zhoumeiling@emc.gov',
    color: '#E6A23C'
  },
  {
    id: 9,
    name: '吴志强',
    role: '后勤保障组长',
    department: '后勤保障科',
    phone: '138-0000-1009',
    email: 'wuzhiqiang@emc.gov',
    color: '#F56C6C'
  },
  {
    id: 10,
    name: '郑晓霞',
    role: '医务工作者',
    department: '医疗救治组',
    phone: '138-0000-1010',
    email: 'zhengxiaoxia@emc.gov',
    color: '#909399'
  },
  {
    id: 11,
    name: '马建军',
    role: '消毒防疫专员',
    department: '消毒防疫科',
    phone: '138-0000-1011',
    email: 'majianjun@emc.gov',
    color: '#409EFF'
  },
  {
    id: 12,
    name: '黄丽娟',
    role: '健康教育专员',
    department: '健康教育科',
    phone: '138-0000-1012',
    email: 'huanglijuan@emc.gov',
    color: '#67C23A'
  },
  {
    id: 13,
    name: '徐国平',
    role: '应急调度员',
    department: '应急指挥中心',
    phone: '138-0000-1013',
    email: 'xuguoping@emc.gov',
    color: '#E6A23C'
  },
  {
    id: 14,
    name: '朱海燕',
    role: '数据分析师',
    department: '数据分析中心',
    phone: '138-0000-1014',
    email: 'zhuhaiyan@emc.gov',
    color: '#F56C6C'
  },
  {
    id: 15,
    name: '何俊杰',
    role: '疫情监测员',
    department: '疫情监测科',
    phone: '138-0000-1015',
    email: 'hejunjie@emc.gov',
    color: '#909399'
  }
];

// 模拟用户组数据
const mockUserGroups = [
  {
    id: 1,
    name: '应急指挥中心',
    icon: 'el-icon-s-flag',
    count: 8,
    description: '负责应急事件的统一指挥调度'
  },
  {
    id: 2,
    name: '流行病学调查组',
    icon: 'el-icon-search',
    count: 12,
    description: '负责疫情的流行病学调查工作'
  },
  {
    id: 3,
    name: '医疗救治组',
    icon: 'el-icon-first-aid-kit',
    count: 15,
    description: '负责患者的医疗救治工作'
  },
  {
    id: 4,
    name: '疾病控制科',
    icon: 'el-icon-news',
    count: 10,
    description: '负责疾病预防控制措施的实施'
  },
  {
    id: 5,
    name: '检验检测中心',
    icon: 'el-icon-data-analysis',
    count: 6,
    description: '负责样本检测和实验室诊断'
  },
  {
    id: 6,
    name: '消毒防疫科',
    icon: 'el-icon-s-tools',
    count: 9,
    description: '负责消毒防疫工作的开展'
  }
];

// 模拟消息历史数据
const mockMessageHistory = [
  {
    id: 'MSG-2025-1101',
    type: '紧急通知',
    title: '紧急启动应急响应机制',
    content: '根据最新疫情研判，决定立即启动二级应急响应机制。请各部门立即进入应急状态，确保24小时值班值守。所有应急人员保持通讯畅通，随时待命。',
    sender: '应急指挥中心',
    sendTime: '2025-11-05 14:30:00',
    recipientCount: 45,
    readCount: 42,
    status: '已发送',
    priority: '高',
    recipients: ['林晓东', '王秀英', '陈国华', '刘敏慧', '杨建国']
  },
  {
    id: 'MSG-2025-1098',
    type: '工作指示',
    title: '关于加强流调工作的通知',
    content: '近期疫情形势复杂，要求流调组加强流行病学调查工作，确保密接追踪到位。所有流调人员务必严格按照工作规范开展调查，及时上报调查结果。',
    sender: '流行病学调查组',
    sendTime: '2025-11-04 10:15:00',
    recipientCount: 12,
    readCount: 12,
    status: '已发送',
    priority: '中',
    recipients: ['王秀英', '赵文静', '何俊杰']
  },
  {
    id: 'MSG-2025-1095',
    type: '信息提醒',
    title: '今日疫情信息汇总',
    content: '今日新增病例3例，密切接触者追踪15人。所有病例均已实施隔离治疗，密接人员落实集中隔离。各部门继续做好疫情防控各项工作。',
    sender: '疫情监测科',
    sendTime: '2025-11-03 18:00:00',
    recipientCount: 35,
    readCount: 30,
    status: '已发送',
    priority: '中',
    recipients: ['林晓东', '杨建国', '郑晓霞', '徐国平']
  },
  {
    id: 'MSG-2025-1089',
    type: '系统公告',
    title: '系统维护通知',
    content: '为提升系统性能，计划于本周六凌晨2:00-6:00进行系统维护升级。维护期间系统将暂停服务，请各位提前做好工作安排。',
    sender: '信息管理科',
    sendTime: '2025-11-02 16:00:00',
    recipientCount: 60,
    readCount: 58,
    status: '已发送',
    priority: '低',
    recipients: ['孙立伟', '朱海燕']
  },
  {
    id: 'MSG-2025-1085',
    type: '紧急通知',
    title: '立即开展核酸检测工作',
    content: '接上级通知，要求立即组织开展全员核酸检测工作。请检验检测中心做好准备，医疗救治组配合采样工作。务必在48小时内完成全部检测任务。',
    sender: '应急指挥中心',
    sendTime: '2025-11-01 09:00:00',
    recipientCount: 28,
    readCount: 28,
    status: '已发送',
    priority: '高',
    recipients: ['周美玲', '郑晓霞', '马建军']
  },
  {
    id: 'MSG-2025-1080',
    type: '工作指示',
    title: '加强环境消杀工作',
    content: '鉴于当前疫情防控需要，要求消毒防疫科加强重点区域的环境消杀工作。对确诊病例活动场所进行终末消毒，公共场所实施预防性消毒。',
    sender: '疾病控制科',
    sendTime: '2025-10-31 14:30:00',
    recipientCount: 9,
    readCount: 9,
    status: '已发送',
    priority: '中',
    recipients: ['马建军', '吴志强']
  },
  {
    id: 'MSG-2025-1075',
    type: '信息提醒',
    title: '健康教育宣传材料已更新',
    content: '已更新最新版本的疫情防控健康教育宣传材料，包括海报、折页和视频等。请各部门及时下载使用，做好群众健康教育工作。',
    sender: '健康教育科',
    sendTime: '2025-10-30 11:00:00',
    recipientCount: 20,
    readCount: 18,
    status: '已发送',
    priority: '低',
    recipients: ['黄丽娟', '徐国平']
  },
  {
    id: 'MSG-2025-1068',
    type: '紧急通知',
    title: '应急物资紧急调配',
    content: '接前线通知，目前防护物资告急。请后勤保障科立即调配防护服500套、N95口罩2000个、消毒液100箱，于今日18:00前送达现场。',
    sender: '后勤保障科',
    sendTime: '2025-10-29 15:00:00',
    recipientCount: 6,
    readCount: 6,
    status: '已发送',
    priority: '高',
    recipients: ['吴志强', '林晓东']
  },
  {
    id: 'MSG-2025-1062',
    type: '工作指示',
    title: '完善数据报送机制',
    content: '为提高疫情信息报送的及时性和准确性，要求数据分析中心优化数据统计流程，建立每日疫情信息快报制度。各相关部门配合做好数据报送工作。',
    sender: '数据分析中心',
    sendTime: '2025-10-28 10:00:00',
    recipientCount: 15,
    readCount: 14,
    status: '已发送',
    priority: '中',
    recipients: ['朱海燕', '孙立伟', '何俊杰']
  },
  {
    id: 'MSG-2025-1055',
    type: '系统公告',
    title: '在线培训通知',
    content: '为提升应急处置能力，定于下周三下午举办突发公共卫生事件应急处置在线培训。请各部门组织人员按时参加，培训内容包括应急预案、处置流程等。',
    sender: '应急管理科',
    sendTime: '2025-10-27 09:30:00',
    recipientCount: 50,
    readCount: 48,
    status: '已发送',
    priority: '低',
    recipients: ['刘敏慧', '林晓东', '王秀英']
  }
];

// 模拟消息统计数据
const mockStatistics = {
  todaySent: 8,
  totalSent: 156,
  readRate: 94,
  pendingSent: 2
};

/**
 * 发送系统消息
 */
export function sendSystemMessage(messageData) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 验证必填字段
      if (!messageData.type) {
        reject(new Error('请选择消息类型'));
        return;
      }
      if (!messageData.title) {
        reject(new Error('请输入消息标题'));
        return;
      }
      if (!messageData.content) {
        reject(new Error('请输入消息内容'));
        return;
      }

      // 计算接收人数
      let recipientCount = 0;
      if (messageData.recipients && messageData.recipients.length > 0) {
        recipientCount += messageData.recipients.length;
      }
      if (messageData.recipientGroups && messageData.recipientGroups.length > 0) {
        messageData.recipientGroups.forEach(groupName => {
          const group = mockUserGroups.find(g => g.name === groupName);
          if (group) {
            recipientCount += group.count;
          }
        });
      }

      // 创建消息记录
      const newMessage = {
        id: `MSG-2025-${Math.floor(Math.random() * 10000)}`,
        type: messageData.type,
        title: messageData.title,
        content: messageData.content,
        sender: '当前用户',
        sendTime: messageData.scheduled ? messageData.scheduledTime : new Date().toLocaleString('zh-CN'),
        recipientCount: recipientCount,
        readCount: 0,
        status: messageData.scheduled ? '待发送' : '已发送',
        priority: messageData.priority,
        recipients: messageData.recipients || []
      };

      // 添加到消息历史
      mockMessageHistory.unshift(newMessage);

      // 更新统计数据
      if (!messageData.scheduled) {
        mockStatistics.todaySent += 1;
        mockStatistics.totalSent += 1;
      } else {
        mockStatistics.pendingSent += 1;
      }

      resolve({ 
        success: true,
        messageId: newMessage.id,
        message: messageData.scheduled ? '消息已定时，将按时发送' : '消息发送成功',
        recipientCount: recipientCount
      });
    }, 1000);
  });
}

/**
 * 获取用户列表
 */
export function getUserList() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockUsers]);
    }, 500);
  });
}

/**
 * 获取用户组列表
 */
export function getUserGroups() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockUserGroups]);
    }, 400);
  });
}

/**
 * 获取消息历史记录
 */
export function getMessageHistory(params = {}) {
  return new Promise((resolve) => {
    setTimeout(() => {
      let results = [...mockMessageHistory];

      // 按消息类型筛选
      if (params.type) {
        results = results.filter(m => m.type === params.type);
      }

      // 按优先级筛选
      if (params.priority) {
        results = results.filter(m => m.priority === params.priority);
      }

      // 按关键词搜索
      if (params.keyword) {
        const keyword = params.keyword.toLowerCase();
        results = results.filter(m => 
          m.title.toLowerCase().includes(keyword) ||
          m.content.toLowerCase().includes(keyword)
        );
      }

      // 按日期范围筛选
      if (params.startDate && params.endDate) {
        results = results.filter(m => {
          const sendDate = m.sendTime.split(' ')[0];
          return sendDate >= params.startDate && sendDate <= params.endDate;
        });
      }

      resolve(results);
    }, 500);
  });
}

/**
 * 获取消息详情
 */
export function getMessageDetail(messageId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const message = mockMessageHistory.find(m => m.id === messageId);
      if (message) {
        resolve(message);
      } else {
        reject(new Error('消息不存在'));
      }
    }, 400);
  });
}

/**
 * 获取消息统计数据
 */
export function getMessageStatistics() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ ...mockStatistics });
    }, 400);
  });
}

/**
 * 撤回消息
 */
export function recallMessage(messageId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const message = mockMessageHistory.find(m => m.id === messageId);
      if (message) {
        // 只能撤回5分钟内发送的消息
        const sendTime = new Date(message.sendTime).getTime();
        const now = new Date().getTime();
        const timeDiff = (now - sendTime) / 1000 / 60; // 分钟

        if (timeDiff > 5) {
          reject(new Error('消息发送超过5分钟，无法撤回'));
          return;
        }

        message.status = '已撤回';
        resolve({ success: true, message: '消息已撤回' });
      } else {
        reject(new Error('消息不存在'));
      }
    }, 800);
  });
}

/**
 * 删除消息
 */
export function deleteMessage(messageId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const index = mockMessageHistory.findIndex(m => m.id === messageId);
      if (index > -1) {
        mockMessageHistory.splice(index, 1);
        resolve({ success: true, message: '消息已删除' });
      } else {
        reject(new Error('消息不存在'));
      }
    }, 600);
  });
}

/**
 * 标记消息已读
 */
export function markMessageAsRead(messageId, userIds) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const message = mockMessageHistory.find(m => m.id === messageId);
      if (message) {
        message.readCount += userIds.length;
        // 确保已读数不超过接收人数
        if (message.readCount > message.recipientCount) {
          message.readCount = message.recipientCount;
        }
      }
      resolve({ success: true });
    }, 500);
  });
}

/**
 * 获取消息阅读详情
 */
export function getMessageReadDetails(messageId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const message = mockMessageHistory.find(m => m.id === messageId);
      if (message) {
        // 模拟阅读详情数据
        const readDetails = {
          messageId: message.id,
          totalRecipients: message.recipientCount,
          readCount: message.readCount,
          unreadCount: message.recipientCount - message.readCount,
          readList: [],
          unreadList: []
        };

        // 随机生成已读和未读用户列表
        const allUsers = [...mockUsers];
        for (let i = 0; i < message.readCount; i++) {
          if (allUsers.length > 0) {
            const randomIndex = Math.floor(Math.random() * allUsers.length);
            const user = allUsers.splice(randomIndex, 1)[0];
            readDetails.readList.push({
              userId: user.id,
              userName: user.name,
              readTime: new Date(Date.now() - Math.random() * 86400000).toLocaleString('zh-CN')
            });
          }
        }

        resolve(readDetails);
      } else {
        reject(new Error('消息不存在'));
      }
    }, 600);
  });
}

